<script >

import title1 from "../components/title.vue";
import Navigation from "../components/navigation_stu.vue";
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus'
import {Refresh, User} from "@element-plus/icons-vue";
export default{
  name: 'stu_personal',
  components:{
    User,
    title1,
    Navigation
  },
  data(){
    return{
      form:{
        stu_id:'',
        stu_name:'',
        stu_sex:'',
        stu_age:'',
        stu_major:'',
        stu_time:'',
        stu_email:''
      },
      // 修改密码相关数据
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: '',
      },
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入当前密码', trigger: 'blur' },
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 3, message: '密码至少为6位', trigger: 'blur' },
        ],
        confirmPassword: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.passwordForm.newPassword) {
                callback(new Error('两次密码不一致'));
              } else {
                callback();
              }
            },
            trigger: 'blur',
          },
        ],
      },
      isPasswordChanging: false,
    
      isEditing: false, // 添加 isEditing 属性
      originalForm: {} // 用于存储原始数据以便取消
    }

  },
  methods:
  {
    async getinfo() {
      try {
          const token = localStorage.getItem('token'); // 确保 token 已正确存储
          // const userNo = sessionStorage.getItem('UserNo'); // 确保 UserNo 已正确存储
          console.log(token);
          // console.log(userNo);
          // 检查 token 和 userNo 是否存在
          if (!token ) {
            alert('缺少必要的认证信息，请重新登录。');
            await this.$router.push({name:"Login"})
            return;
            }

          const response = await axios.post(`${import.meta.env.VITE_API_BASE_URL}/student/showStudentInfo`, null, {
            headers: {
              token: token
            },
            
          });

          if (response.data.code === '200') {
            console.log(response.data.data)
            this.form.stu_id = response.data.data.s_no;
            this.form.stu_name = response.data.data.s_name;
            this.form.stu_sex = response.data.data.s_sex;
            this.form.stu_age = response.data.data.s_age;
            this.form.stu_phone = response.data.data.s_phone;
            this.form.stu_major = response.data.data.s_major;
            this.form.stu_time = response.data.data.s_time;
            this.form.stu_email = response.data.data.s_email;
            
          } else {
            alert('获取信息失败');
          }
        } catch (error) {
        console.error('获取信息失败', error);
        alert('获取信息出错，请稍后再试');
        }
    },

    enableEditing() {
      this.isEditing = true; // 启用编辑模式
    },
    async saveInfo() {
      //*添加保存逻辑，例如调用 API 保存数据
      try{
        const response = await axios.post(`${import.meta.env.VITE_API_BASE_URL}/student/modifyStudentInfo`,

        {
        s_email: this.form.stu_email
        },

        {
          headers: {
            token: localStorage.getItem('token')
          }
        });
        if (response.data.code === '200') {
          ElMessage({
            type: 'success',
            message: '保存成功'
          });
        } else {
          ElMessage({
            type: 'error',
            message: '保存失败'
          });
        }
      } catch (error) {
        console.error('保存信息失败', error);
        alert('保存信息出错，请稍后再试');
      }
      
    
      this.getinfo(); // 重新获取数据





      // 保存成功后设置 isEditing 为 false
      this.isEditing = false;
      
    },
    cancelEdit() {
      this.getinfo(); // 重新获取数据
      this.isEditing = false; // 取消编辑模式
    },
    open() {
      ElMessageBox.confirm(
        '确定保存吗',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          this.saveInfo() // 若确认，转入saveInfo
          
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消保存',
          })
        })
    },
    Refresh(){
      this.getinfo();
      ElMessage({
        type:'success',
        message:'刷新成功',
      })
    },
    // 修改密码方法
    confirmChangePassword() {
      this.$confirm('确定修改密码吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.handlePasswordChange();
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消修改密码',
          });
        });
    },
    handlePasswordChange() {
      this.$refs.passwordFormRef.validate(async (valid) => {
        if (valid) {
          this.isPasswordChanging = true;
          try {
            const response = await axios.post(`${import.meta.env.VITE_API_BASE_URL}/updatepsw`, null,
            {
              params: {
                oldpsw: this.passwordForm.oldPassword,
                newpsw: this.passwordForm.newPassword,
              },
              headers: {
                token: localStorage.getItem('token'),
              },
            });
            console.log(this.passwordForm.oldPassword);
            console.log(this.passwordForm.oldPassword);
            console.log(response);
            if (response.data.code == '200') {
              ElMessage.success('密码修改成功');
              localStorage.removeItem('token')
              this.$router.push({name:"Login"})
            } else {
              ElMessage.error(response.data.message || '密码修改失败');
            }
          } catch (error) {
            ElMessage.error('网络错误，请稍后再试');
            console.error(error);
          }
          this.isPasswordChanging = false;
        }
      });
    },
    // 重置密码表单
    resetPasswordForm() {
      this.$refs.passwordFormRef.resetFields();
      
    },

    
  },
  mounted() {
    this.getinfo();
    document.title = '学生信息管理系统';
    const token = localStorage.getItem('token'); // 确保 token 已正确存储
    const userNo = sessionStorage.getItem('UserNo'); // 确保 UserNo 已正确存储
    if (!token || !userNo) {
      alert('缺少必要的认证信息，请重新登录。');
      this.$router.push({ name: "Login" });
    }
  }
}

</script>

<template class="dark">
  <text class="sub-title">— 查看个人信息</text>
  
  <title1></title1>
  
  <Navigation></Navigation>
  <el-scrollbar wrap-class="scrollbar-wrapper" style="height: 100vh;">
    <el-main>
      <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>
            <el-icon><User/></el-icon>查看个人信息
          </span>
        </div>
      </template>
      <el-row>
        <el-col :span="12">
          <el-form label-position="left" label-width="80px">
            <el-form-item label="学号">
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="无法更改，请联系管理员更改"
                  placement="right"
                >
                <el-input v-model="form.stu_id" disabled></el-input>
               </el-tooltip>
            </el-form-item>
            <el-form-item label="姓名">
              <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="无法更改，请联系管理员更改"
                  placement="right"
                >
                <el-input v-model="form.stu_name"  disabled></el-input>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="性别">
              <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="无法更改，请联系管理员更改"
                  placement="right"
                >
                <el-input v-model="form.stu_sex"  disabled></el-input>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="年龄">
              <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="无法更改，请联系管理员更改"
                  placement="right"
                >
                <el-input v-model="form.stu_age"  disabled></el-input>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-tooltip
                  class="box-item"
                  effect="light"
                  content="可以更改"
                  placement="right"
                >
                <el-input v-model="form.stu_email"  :disabled="!isEditing"></el-input>
              </el-tooltip>
            </el-form-item>
          </el-form>
        </el-col>  
      </el-row>
     
        <el-button type="primary" @click="Refresh">刷新</el-button>
        <template v-if="!isEditing">
          <el-button type="primary" @click="enableEditing">修改</el-button>
        </template>      
        <template v-else>         
          <el-button type="success" @click="open">保存</el-button>         
          <el-button type="warning" @click="cancelEdit">取消</el-button>
        </template>
      
        
      </el-card>
    


       <!-- 修改密码卡片 -->
  <el-card class="password-change-card" >
    <template #header>
        <div class="card-header">
          <span>
            <el-icon><User/></el-icon>修改密码
          </span>
        </div>
      </template>
    <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="120px" class="password-form">
      <el-form-item label="当前密码" prop="currentPassword">
        <el-input
          type="password"
          v-model="passwordForm.oldPassword"
          placeholder="请输入当前密码"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          type="password"
          v-model="passwordForm.newPassword"
          placeholder="请输入新密码"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmPassword">
        <el-input
          type="password"
          v-model="passwordForm.confirmPassword"
          placeholder="请确认新密码"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="修改后会重新登陆"
                  placement="right"
                  >
                  <el-button type="primary" @click="confirmChangePassword" :loading="isPasswordChanging">修改密码</el-button>
          </el-tooltip>
        <el-button @click="resetPasswordForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</el-main>

</el-scrollbar>
  
</template>

<style scoped >
.sub-title{
  z-index: 2;
  position: fixed;
  top: 35px;
  left: 380px;
  color: #0e4bbd;
  font-size: 30px;
  font-weight: normal;
}
.box-card {
  position:fixed;
  top:100px;
  width:83%;
  left:250px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
/* 修改密码卡片样式 */
.password-change-card {
  position: fixed;
  top: 500px;
  width: 83%;
  left: 250px;
  
  
}

.password-change-card h2 {
  margin-bottom: 20px;
  color: #333;
}

.password-form {
  max-width: 50%;
}

.card-actions {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

</style>